import store from '@/store';
import router from '@/router';
import { ApiMenu } from '@/axios/api';
import { Result } from '@/model/common';
import { Menu } from '@/model/common/Menu';
import { ObjectUtil } from '@/util';

export default class MenuUtil {
    /**
     * 加载菜单信息
     */
    public static loadMenu(): Promise<Menu[]> {
        return new Promise((resolve, reject) => {
            ApiMenu.currentList()
                .then((res: Result) => {
                    const menus: Menu[] = [];
                    res.data.forEach((item: any) => {
                        const menu = new Menu();
                        ObjectUtil.copy(item, menu);
                        menus.push(menu);
                    });
                    store.commit('menus', menus);
                    resolve(menus);
                })
                .catch((err: Result) => {
                    reject(err);
                });
        });
    }

    /**
     * 菜单跳转
     */
    public static defautlSkip(menus: Menu[]) {
        for (const [, menu] of menus.entries()) {
            if (menu.children) {
                this.defautlSkip(menu.children);
            } else if (!menu.enabled || !menu.display || menu.link) {
                continue;
            } else if (menu.url) {
                router.push(menu.url);
                break;
            }
        }
    }
}
